#include "Resource.h"
#include "../lua/lua.hpp"

Resource* _res;
lua_State* g_L = NULL;

static int res_find(lua_State* L) {
	const char* name = lua_tostring(L, -1);
	unsigned int id = _res->find_node(name);
	lua_pop(L, 1);
	lua_pushinteger(L, id);
	return 1;
}

static int res_add_dir(lua_State* L) {
	const char* dir_name = lua_tostring(L, -1);
	unsigned int id = _res->add_dir(dir_name);
	lua_pop(L, 1);
	lua_pushinteger(L, id);
	return 1;
}

static int res_add_string(lua_State* L) {
	const char* str = lua_tostring(L, -1);
	const char* name = lua_tostring(L, -2);
	unsigned int len = strlen(str) + 1;
	unsigned int id = _res->add_node(name, 1, len);
	memcpy(_res->datas[id], name, len);
	lua_pop(L, 2);
	lua_pushinteger(L, id);
	return 1;
}

static int res_add_file(lua_State* L) {
	const char* file_name = lua_tostring(L, -1);
	const char* name = lua_tostring(L, -2);
	unsigned int id = _res->add_file(name, file_name);
	lua_pop(L, 2);
	lua_pushinteger(L, id);
	return 1;
}

static int res_show(lua_State* L) {
	unsigned int id = 0;
	if(lua_type(L, -1) == LUA_TSTRING) id = _res->find_node(lua_tostring(L, -1));
	else id = lua_tointeger(L, -1);
	if(!id) return 0;
	if(_res->IDs[id].version == 0) {
		unsigned char* ptr = (unsigned char*)_res->load_id(id);
		printf("dir--\n");
		while(*ptr) {
			char name[1024];
			memcpy(name, ptr + 1, *ptr);
			name[*ptr] = 0;
			ptr += *ptr + 1;
			printf("%s[%d]\n", name, *(unsigned int*)ptr);
			ptr += sizeof(unsigned int);
		}
		printf("--\n");
	}
	else {
		printf("%d-%d-%d\n", _res->IDs[id].version, _res->IDs[id].pos, _res->IDs[id].size);
	}
	return 0;
}

static luaL_Reg reslib[] = {  
    {"find", res_find},
    {"add_dir", res_add_dir},
    {"add_string", res_add_string},  
	{"add_file", res_add_file},
	{"show", res_show},
    {NULL, NULL}
};  

LUAMOD_API int luaopen_res(lua_State *L) {
  luaL_newlib(L, reslib);
  return 1;
}

void res_init(const char* res_name) {
	_res = new Resource(res_name, 10240);
	g_L = luaL_newstate();
	luaL_openlibs(g_L);
	if(g_L) {
		luaL_requiref(g_L, "res", luaopen_res, 1);
	}
}

void res_console() {
	char line[1024];
	while(true) {
		gets(line);
		if(!memcmp(line, "exit", 4)) return;
		luaL_dostring(g_L, line);
	}
}

void res_exit() {
	if(g_L) lua_close(g_L);
	delete _res;
}